﻿using Entity;
using Microsoft.AspNetCore.Http;
using ServiceCore;
using ServiceCore.Tool.Pic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Customer.Bussiness_Service
{
    public interface Iwarehouse_base_service
    {
        /// <summary>
        /// 保存仓库 区域信息
        /// </summary>
        /// <param name="base_id"></param>
        /// <param name="base_name"></param>
        /// <param name="parent_id"></param>
        /// <returns></returns>
        ResultObjModel save_warehouse(string base_id, string base_name, string parent_id = "0");
        /// <summary>
        /// 获取仓库列表
        /// </summary>
        /// <param name="parent_id"></param>
        /// <returns></returns>
        ResultObjModel get_warehouse(string parent_id = "0");
        /// <summary>
        /// 设置仓库状态
        /// </summary>
        /// <param name="base_id"></param>
        /// <param name="warehouse_base_state"></param>
        /// <returns></returns>
        ResultObjModel set_warehouse_state(string base_id, warehouse_base_state? warehouse_base_state);
        /// <summary>
        /// 获取可用的仓库状态树
        /// </summary>
        /// <returns></returns>
        ResultObjModel get_warehouse_tree();
        /// <summary>
        /// 保存库位设置信息
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultObjModel save_warehouse_position(save_warehouse_position_params Params);
        /// <summary>
        /// 设置库位物料
        /// </summary>
        /// <param name="warehouse_position_id"></param>
        /// <param name="materiel_id"></param>
        /// <returns></returns>
        ResultObjModel set_warehouse_position_materiel(string warehouse_position_id, string materiel_id);
        /// <summary>
        /// 设置库位状态
        /// </summary>
        /// <param name="warehouse_position_id"></param>
        /// <param name="warehouse_position_state"></param>
        /// <returns></returns>
        ResultObjModel set_warehouse_position_state(string warehouse_position_id, warehouse_position_state? warehouse_position_state);
        /// <summary>
        /// 库位列表查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel<search_warehouse_position_item> get_pagelist(search_warehouse_position_params query);
    }
    public class warehouse_base_service : Iwarehouse_base_service
    {
        private readonly IToole_DI _tool;
        private readonly IHttpContextAccessor _context;
        private readonly ICacheHelper _cache;

        public warehouse_base_service(IToole_DI Tool, IHttpContextAccessor Context, ICacheHelper Cache)
        {
            _tool = Tool;
            _context = Context;
            _cache = Cache;
        }
        /// <summary>
        /// 保存仓库信息
        /// </summary>
        /// <returns></returns>
        public ResultObjModel save_warehouse(string base_id, string base_name, string parent_id = "0")
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(base_name))
                {
                    result.code = 1;
                    result.msg = $"{(parent_id == "0" ? "仓库名称" : "区域名称")}不能为空";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(base_id))
                {
                    base_id = "";
                }
                if (string.IsNullOrWhiteSpace(parent_id))
                {
                    parent_id = "0";
                }
                //检测同级别名称是否为空
                int check_warehouse = _tool.di_db.GetList<int>("select count(*) from warehouse_base where parent_id=@parent_id and base_name=@base_name and base_id<>@base_id", new { base_id, base_name, parent_id }).FirstOrDefault();
                if (check_warehouse > 0)
                {
                    result.code = 1;
                    result.msg = $"{(parent_id == "0" ? "仓库名称" : "区域名称")}已存在";
                    return result;
                }
                int tran_rows = 0;
                if (string.IsNullOrWhiteSpace(base_id))
                {
                    warehouse_base new_mod = new warehouse_base()
                    {
                        base_id = _tool.di_getid.IGet_SnowFlake_Id,
                        addtime = DateTime.Now,
                        adduser = _tool.di_user.USER.uid,
                        base_name = base_name,
                        parent_id = parent_id,
                        warehouse_data_type = parent_id == "0" ? warehouse_data_type.仓库 : warehouse_data_type.区域,
                        warehouse_base_state = warehouse_base_state.启用
                    };
                    tran_rows = _tool.di_db.Add(new_mod);
                }
                else
                {
                    //检测更新数据是否存在
                    warehouse_base update_item = _tool.di_db.GetList<warehouse_base>("select top 1 * from warehouse_base where base_id=@base_id", new { base_id }).FirstOrDefault();
                    if (update_item == null)
                    {
                        result.code = 1;
                        result.msg = "待更新数据不存在";
                        return result;
                    }
                    update_item.base_name = base_name;
                    //update_item.parent_id = parent_id;//反正他这个页面设计也改不了。。干脆别让改了 本来前端就容易乱
                    update_item.warehouse_data_type = parent_id == "0" ? warehouse_data_type.仓库 : warehouse_data_type.区域;
                    tran_rows = _tool.di_db.Update<warehouse_base>(new string[] { "base_name", "warehouse_data_type" }, new string[] { "base_id=@base_id" }, update_item);
                }
                if (tran_rows > 0)
                {
                    result.code = 0;
                    result.msg = "保存成功";
                    _tool.ref_warehouse_list();

                }
                else
                {
                    result.code = 1;
                    result.msg = "保存失败";
                }
                return result;
            });
        }
        /// <summary>
        /// 获取仓库信息
        /// </summary>
        /// <returns></returns>
        public ResultObjModel get_warehouse(string parent_id = "0")
        {
            return CoreStartDo.ResultAction(result =>
            {
                result.code = 0;
                result.msg = "success";
                result.data = _tool.get_warehouse_list.Where(s => s.parent_id == parent_id);
                return result;
            });
        }
        /// <summary>
        /// 设置仓库状态
        /// </summary>
        /// <returns></returns>
        public ResultObjModel set_warehouse_state(string base_id, warehouse_base_state? warehouse_base_state)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(base_id))
                {
                    result.code = 1;
                    result.msg = "关键参数未入参";
                    return result;
                }
                if (!warehouse_base_state.HasValue)
                {
                    result.code = 1;
                    result.msg = "仓库状态未设置";
                    return result;
                }
                //开始更新
                int set_rows = _tool.di_db.do_Execute("update warehouse_base set warehouse_base_state=@warehouse_base_state where base_id=@base_id", new { base_id, warehouse_base_state });
                if (set_rows > 0)
                {
                    result.code = 0;
                    result.msg = "保存成功";
                    _tool.ref_warehouse_list();
                }
                else
                {
                    result.code = 1;
                    result.msg = "保存失败";
                }
                return result;
            });
        }

        /// <summary>
        /// 获取所有启用状态的仓库区域对应关系
        /// </summary>
        /// <returns></returns>
        public ResultObjModel get_warehouse_tree()
        {
            return CoreStartDo.ResultAction(result =>
            {
                var all_list = _tool.get_warehouse_list.Where(s => s.warehouse_base_state == warehouse_base_state.启用);
                result.code = 0;
                result.msg = "success";
                result.data = from o in all_list.Where(s => s.parent_id == "0")
                              select new
                              {
                                  o.base_id,
                                  o.base_name,
                                  o.parent_id,
                                  children = from x in all_list.Where(s => s.parent_id == o.base_id)
                                             select new
                                             {
                                                 x.base_id,
                                                 x.base_name,
                                                 x.parent_id,
                                             }
                              };
                return result;
            });
        }

        #region 库位设置
        /// <summary>
        /// 设置库位信息
        /// </summary>
        /// <returns></returns>
        public ResultObjModel save_warehouse_position(save_warehouse_position_params Params)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(Params.warehouse_position_id))
                {
                    Params.warehouse_position_id = "";
                }
                if (string.IsNullOrWhiteSpace(Params.warehouse_id))
                {
                    result.code = 1;
                    result.msg = "请选择所属仓库";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(Params.warehouse_area_id))
                {
                    result.code = 1;
                    result.msg = "请选择所属仓库区域";
                    return result;
                }
                if (!Params.warehouse_position_type.HasValue)
                {
                    result.code = 1;
                    result.msg = "请选择库位类型";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(Params.letter_type_No))
                {
                    result.code = 1;
                    result.msg = "定义库位信息参数不完整:中间段未设置";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(Params.custom_type_No))
                {
                    result.code = 1;
                    result.msg = "定义库位信息参数不完整:自定义项未设置";
                    return result;
                }
                //拼出来一个当前设置的库位号
                string[] first_array = new string[] { "T", "H" };
                try
                {
                    string Tinfo = first_array[(int)Params.warehouse_position_type.Value - 1];
                }
                catch
                {
                    result.code = 1;
                    result.msg = "设置库位类型异常";
                    return result;
                }
                string complete_type_No = $"{first_array[(int)Params.warehouse_position_type.Value - 1]}-{Params.letter_type_No}-{Params.custom_type_No}";
                //检测该库位是否存在
                int check_exite = _tool.di_db.GetList<int>("select count(*) from warehouse_position where complete_type_No=@complete_type_No and warehouse_position_id<>@warehouse_position_id", new { complete_type_No, Params.warehouse_position_id }).FirstOrDefault();
                if (check_exite > 0)
                {
                    result.code = 1;
                    result.msg = "库位已存在,请检查相关信息";
                    return result;
                }
                int tran_rows = 0;
                if (string.IsNullOrWhiteSpace(Params.warehouse_position_id))
                {
                    warehouse_position new_mod = new warehouse_position()
                    {
                        warehouse_position_id = _tool.di_getid.IGet_SnowFlake_Id,
                        addtime = DateTime.Now,
                        adduser = _tool.di_user.USER.uid,
                        complete_type_No = complete_type_No,
                        custom_type_No = Params.custom_type_No,
                        letter_type_No = Params.letter_type_No,
                        materiel_id = "",
                        type_No = first_array[(int)Params.warehouse_position_type.Value - 1],
                        warehouse_area_id = Params.warehouse_area_id,
                        warehouse_id = Params.warehouse_id,
                        warehouse_position_type = Params.warehouse_position_type.Value,
                        warehouse_position_state = warehouse_position_state.启用
                    };
                    tran_rows = _tool.di_db.Add(new_mod);
                }
                else
                {
                    //检测更新库位是否已定义
                    var check_position = _tool.di_db.GetList<warehouse_position>("select top 1 * from warehouse_position where warehouse_position_id=@warehouse_position_id", new { Params.warehouse_position_id }).FirstOrDefault();
                    if (check_position == null)
                    {
                        result.code = 1;
                        result.msg = "编辑数据不存在";
                        return result;
                    }
                    check_position.complete_type_No = complete_type_No;
                    check_position.custom_type_No = Params.custom_type_No;
                    check_position.letter_type_No = Params.letter_type_No;
                    check_position.type_No = first_array[(int)Params.warehouse_position_type.Value - 1];
                    check_position.warehouse_area_id = Params.warehouse_area_id;
                    check_position.warehouse_id = Params.warehouse_id;
                    check_position.warehouse_position_type = Params.warehouse_position_type.Value;
                    tran_rows = _tool.di_db.Update<warehouse_position>(new string[] {
                        "complete_type_No","custom_type_No","letter_type_No","type_No","warehouse_area_id","warehouse_position_type","warehouse_id"
                    }, new string[] { "warehouse_position_id=@warehouse_position_id" }, check_position);
                }
                if (tran_rows > 0)
                {
                    result.code = 0;
                    result.msg = "保存成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "保存失败";
                }
                return result;
            });
        }
        /// <summary>
        /// 设置库位堆放物料
        /// </summary>
        /// <returns></returns>
        public ResultObjModel set_warehouse_position_materiel(string warehouse_position_id, string materiel_id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(warehouse_position_id))
                {
                    result.code = 1;
                    result.msg = "库位信息不能为空";
                    return result;
                }
                int tran_rows = 0;
                if (string.IsNullOrWhiteSpace(materiel_id))
                {
                    tran_rows = _tool.di_db.do_Execute("update warehouse_position set materiel_id=@materiel_id where warehouse_position_id=@warehouse_position_id", new { warehouse_position_id, materiel_id = "" });
                }
                else
                {
                    //确认物料信息真实存在
                    materiel_base check_materiel = _tool.di_db.GetList<materiel_base>("select top 1 * from materiel_base where materiel_id=@materiel_id", new { materiel_id }).FirstOrDefault();
                    if (check_materiel == null)
                    {
                        result.code = 1;
                        result.msg = "物料信息不存在";
                        return result;
                    }
                    else
                    {
                        tran_rows = _tool.di_db.do_Execute("update warehouse_position set materiel_id=@materiel_id where warehouse_position_id=@warehouse_position_id", new { warehouse_position_id, materiel_id });
                    }
                }
                
                if (tran_rows > 0)
                {
                    result.code = 0;
                    result.msg = "设置成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "设置失败";
                }
                return result;
            });
        }
        /// <summary>
        /// 设置库位状态
        /// </summary>
        /// <returns></returns>
        public ResultObjModel set_warehouse_position_state(string warehouse_position_id, warehouse_position_state? warehouse_position_state)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(warehouse_position_id))
                {
                    result.code = 1;
                    result.msg = "库位信息不能为空";
                    return result;
                }
                if (!warehouse_position_state.HasValue)
                {
                    result.code = 1;
                    result.msg = "请选择库位状态";
                    return result;
                }
                int tran_rows = _tool.di_db.do_Execute("update warehouse_position set warehouse_position_state=@warehouse_position_state where warehouse_position_id=@warehouse_position_id", new { warehouse_position_id, warehouse_position_state });
                if (tran_rows > 0)
                {
                    result.code = 0;
                    result.msg = "设置成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "设置失败";
                }
                return result;
            });
        }
        /// <summary>
        /// 列表查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel<search_warehouse_position_item> get_pagelist(search_warehouse_position_params query)
        {
            return CoreStartDo.ResultAction<ResultListModel<search_warehouse_position_item>>(result =>
            {
                string sql = "select a.*,b.materiel_name,b.materiel_pic,b.materiel_total_show_no,b.specifications,b.unit,b.use_des from warehouse_position a left join materiel_base b on a.materiel_id = b.materiel_id";
                string where = " where 1=1";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                if (!string.IsNullOrWhiteSpace(query.warehouse_id))
                {
                    where += " and a.warehouse_id=@warehouse_id";
                    query_dy.warehouse_id = query.warehouse_id;
                }
                if (!string.IsNullOrWhiteSpace(query.warehouse_area_id))
                {
                    where += " and a.warehouse_area_id=@warehouse_area_id";
                    query_dy.warehouse_area_id = query.warehouse_area_id;
                }
                if (!string.IsNullOrWhiteSpace(query.complete_type_No))
                {
                    where += " and a.complete_type_No like @complete_type_No";
                    query_dy.complete_type_No = $"%{ query.complete_type_No }%";
                }
                if (!string.IsNullOrWhiteSpace(query.specifications))
                {
                    where += " and b.specifications like @specifications";
                    query_dy.specifications = $"%{ query.specifications }%";
                }
                if (query.search_type.HasValue)
                {
                    switch (query.search_type.Value)
                    {
                        case warehouse_position_searchtype.物料编号:
                            where += " and b.materiel_total_show_no like @materiel_total_show_no";
                            query_dy.materiel_total_show_no = $"%{ query.search_value }%";
                            break;
                        case warehouse_position_searchtype.物料名称:
                            where += " and b.materiel_name like @materiel_name";
                            query_dy.materiel_name = $"%{ query.search_value }%";
                            break;
                    }
                }
                result = _tool.di_db.GetPageList<search_warehouse_position_item>(sql, where, "a.addtime", query_dy, query.IsPage, query.page, query.pagesize);
                foreach (var item in result.rows)
                {
                    item.warehouse_name = _tool.get_warehouse_list.Where(s => s.base_id == item.warehouse_id).Any() ? _tool.get_warehouse_list.Where(s => s.base_id == item.warehouse_id).FirstOrDefault().base_name : "";
                    item.warehouse_area_name = _tool.get_warehouse_list.Where(s => s.base_id == item.warehouse_area_id).Any() ? _tool.get_warehouse_list.Where(s => s.base_id == item.warehouse_area_id).FirstOrDefault().base_name : "";
                }
                return result;
            });
        }
        #endregion
    }
}
